package top.yfq.multidatasource.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import top.yfq.multidatasource.constant.DataSourceType;
import top.yfq.multidatasource.tenant.TenantContextHolder;

import java.util.Objects;


/**
 * @author yfq
 * @date 2025/9/26 22:35
 * @description 动态数据源
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final IDataSourceService dataSourceService;

    public DynamicDataSource(IDataSourceService dataSourceService) {
        this.dataSourceService = dataSourceService;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        Long tenantId = TenantContextHolder.getTenantId();
        if (tenantId == null) return null;

        DataSourceInfo dataSourceInfo = dataSourceService.queryByKey(String.valueOf(tenantId));
        if (dataSourceInfo == null) throw new RuntimeException("DataSource not exist!");

        if (Objects.equals(dataSourceInfo.getType(), DataSourceType.SHARED.getType())) return null;

        return dataSourceInfo.getKey();
    }
}
